//
//  SaveImageToAlbumManager.swift
//  SwiftProject
//
//  Created by 董駸 on 2022/8/10.
//

import UIKit
import Photos

class SaveImageToAlbumManager: NSObject {
    static let shared = SaveImageToAlbumManager()
    var album : QMUIAssetsGroup?

    private override init() {}
    
    func getAlbumList() -> [QMUIAssetsGroup] {
        var albumList : [QMUIAssetsGroup] = []
        QMUIAssetsManager.sharedInstance().enumerateAllAlbums(with: .all, showEmptyAlbum: true, showSmartAlbumIfSupported: false) { resultAssetsGroup in
            if resultAssetsGroup != nil {
                albumList.append(resultAssetsGroup!)
            }
        }
        return albumList
    }
    
    func handleSaveToAlbum(_ image : UIImage, _ album : QMUIAssetsGroup) {
        if QMUIAssetsManager.authorizationStatus() == .notDetermined {
            QMUIAssetsManager.requestAuthorization { status in
                DispatchQueue.main.async {
                    if status == .authorized {
                        self.saveImageToAlbum(image, album)
                    } else {
                        DHelper.showAlertWhenSavedPhotoFailureByPermissionDenied()
                    }
                }
            }
        } else if QMUIAssetsManager.authorizationStatus() == .notAuthorized {
            DHelper.showAlertWhenSavedPhotoFailureByPermissionDenied()
        } else {
            saveImageToAlbum(image, album)
        }
    }
    
    private func saveImageToAlbum(_ image : UIImage, _ album : QMUIAssetsGroup) {
        QMUIImageWriteToSavedPhotosAlbumWithAlbumAssetsGroup(image, album) { asset, error in
            if asset != nil {
                QMUITips.showSucceed("已保存到相册-\(album.name()!)")
            }
        }
    }
    
    func createAlbumWithName(_ name : String? = nil) {
        var name = name
        if name == nil {
            name = AppName
        }
        PHPhotoLibrary.shared().performChanges {
            PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: name!)
        } completionHandler: { success, error in
            self.album = self.getAlbumList().filter{ $0.name()! == name }.first
        }
    }
}
